package com.fly.simple.utils;

import java.io.IOException;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

/**
 * 
 * FreeMarkers
 * 
 * @author 00fly
 * @version [版本号, 2017-4-4]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
public class FreeMarkerUtil
{
    private static Configuration config;
    
    static
    {
        config = new Configuration(Configuration.VERSION_2_3_32);
        config.setDefaultEncoding(StandardCharsets.UTF_8.name());
    }
    
    /**
     * 获取模板填充model解析后的内容
     * 
     * @param template
     * @param model
     * @return
     * @throws IOException
     * @throws TemplateException
     * @see [类、类#方法、类#成员]
     */
    private static String renderTemplate(Template template, Map<String, Object> model)
        throws TemplateException, IOException
    {
        StringWriter result = new StringWriter();
        template.process(model, result);
        return result.toString();
    }
    
    /**
     * 获取模板填充model后的内容
     * 
     * @param templatePath
     * @param model
     * @return
     * @throws IOException
     * @throws TemplateException
     * @see [类、类#方法、类#成员]
     */
    public static String renderTemplate(String templatePath, Map<String, Object> model)
        throws TemplateException, IOException
    {
        config.setClassForTemplateLoading(FreeMarkerUtil.class, "/");
        Template template = config.getTemplate(templatePath);
        return renderTemplate(template, model);
    }
}